# encoding: utf-8
require "logstash/filters/base"
require "logstash/namespace"
require "logstash/environment"
###still has issues, when watch keywords, the next matched keyword value will not be summed
class LogStash::Filters::Sumts < LogStash::Filters::Base
    config_name("sumts")
    milestone 1

    config :ts_field, :validate => :string, :required => false
    config :input_field, :validate => :string
    config :output_field, :validate => :string, :default => 'sum'
    config :keywords, :validate => :array, :required => false
    
    public
    def register
        @last_event = nil
        @kv_dict = {} # dict<keywords_combined, sum_value>
        @flush = true
    end

    public
    def filter(event)
        has_input_field = event.include?(@input_field)
        event['has_input_field'] = has_input_field
        
        current_event = event
        current_ts = event[@ts_field].to_s
        last_ts = nil
        if !@last_event.nil?
            last_ts = @last_event[@ts_field].to_s
            event['current_ts'] = current_ts
            event['last_ts'] = last_ts
        end
###### checking whether all keywords chosen to watch exist or not
        all_keywords_exists = true
        combined_key = 'prefix_'
        if !@keywords.nil?
            @keywords.each do |kw|
                combined_key += event[kw.to_s].to_s
                if !event.include?(kw.to_s)
                    all_keywords_exists = false
                    break
                end
            end
        end
###### timestamp flipped
        if !last_ts.nil? and current_ts != last_ts# and !@kv_dict.empty?
            event['debug_fliped'] = true
            event[@output_field] = @kv_dict[combined_key]
            @flush = true
        end
###### 
        #has_ts_field = true
        has_ts_field = event.include?(@ts_field)
        event['has_ts_field'] = has_ts_field
        if has_input_field and has_ts_field and all_keywords_exists
            if !@flush
                event['beforeAdd'] = @kv_dict.to_s
                @kv_dict[combined_key] = @kv_dict[combined_key].to_f + event[@input_field].to_f
                event['afterAdd'] = @kv_dict.to_s
            else
                event['assignVal'] = true
                @kv_dict = {}
                @kv_dict[combined_key] = event[@input_field].to_f
                @flush = false
            end

            event['debug_2'] = @kv_dict.to_s
            @last_event = current_event
        end        
    end #end of def filter
end # class LogStash::Filters::Sum
